package com.gshrms.common.utils;


import com.alibaba.fastjson2.JSONObject;
import com.gshrms.common.annotation.Excel;
import com.gshrms.common.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

public class CustomExcelUtil<T> extends ExcelUtil<T> {


    public CustomExcelUtil(Class<T> clazz) {
        super(clazz);
    }
    @Override
    public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title) {
        // 1. 获取有效字段列表（过滤全为null的字段）
        List<Field> validFields = Arrays.stream(clazz.getDeclaredFields())
                .filter(field -> {
                    field.setAccessible(true);
                    return list.stream().anyMatch(obj -> {
                        try {
                            return field.get(obj) != null;
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }
                    });
                })
                .collect(Collectors.toList());

        // 2. 构建符合若依框架要求的数据格式
        List<Map<String, Object>> dataList = list.stream().map(obj -> {
            Map<String, Object> row = new LinkedHashMap<>();
            validFields.forEach(field -> {
                try {
                    String columnName = Optional.ofNullable(field.getAnnotation(Excel.class))
                            .map(Excel::name)
                            .orElse(field.getName());
                    row.put(columnName, field.get(obj));
                } catch (IllegalAccessException e) {
                    row.put(field.getName(), "");
                }
            });
            return row;
        }).collect(Collectors.toList());

        System.out.println("data:"+dataList.toString());

        // 3. 调用父类方法导出（需重写部分逻辑）
        super.exportExcel(response, (List<T>) dataList, sheetName, title);
    }
}
